<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use think\Validate;
use cmf\controller\HomeBaseController;
use app\user\model\UserModel;
use think\Db;
class LoginController extends HomeBaseController
{
    /*
     *
     * 登录
     */
    public function index()
    {
        $redirect = $this->request->post("redirect");
        if (empty($redirect)) {
            $redirect = $this->request->server('HTTP_REFERER');
        } else {
            $redirect = base64_decode($redirect);
        }
        session('login_http_referer', $redirect);
        if (cmf_is_user_login()) { //已经登录时直接跳到首页
            return redirect($this->request->root() . '/home/menu/menu');
        } else {
            return $this->fetch(":login");
        }
    }

    /*
     *
     * 登录验证提交
     */
    public function doLogin()
    {
//        var_dump($this->request->param());exit();
        if ($this->request->param()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
                'password.max'     => '密码不能超过32个字符',
                'password.min'     => '密码不能小于6个字符',
            ]);

            $data = $this->request->param();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $passs = cmf_password($data['password']);
            //判断用户是否是首次登陆
            $uinfo = Db::name("user")->count();
             if($uinfo == 0){
                 $this->success('账户初始化，请等待...',url('api/Tongbu/initialize',array('username'=>$data['username'],'password'=>$data['password'])));
             }
             $uinfo = Db::name("user")->where("mobile=".$data['username'])->find();
             if(empty($uinfo)){
                 $this->error('账户不存在');exit;
             }
            //更新数据表字段类型 ---order表中orderNo为唯一类型
            $sqls = "show index from mt_order where key_name like 'orderNo'";
            $sum = Db::execute($sqls);
            if($sum < 1){
                $sql = "ALTER IGNORE TABLE `mt_order` ADD UNIQUE (`orderNo`)";
                $result = Db::execute($sql);
            }

            //判断order_detail表中是否存在小计total
            $order = "SELECT * FROM information_schema.columns WHERE table_name='mt_order_detail'  and column_name='total'";
            $orderTotal = Db::query($order);
            if($orderTotal == false){
                //插入表字段 ---------order_detail表中添加小计
                $sqlt = "ALTER TABLE `mt_order_detail` ADD `total` DECIMAL (11,2) NOT NULL default '0'";
                $rest = Db::execute($sqlt);
            }
            //判断order_detail表中是否存在数量count
            $order = "SELECT * FROM information_schema.columns WHERE table_name='mt_order_detail'  and column_name='count'";
            $orderTotal = Db::query($order);
            if($orderTotal == false){
                //插入表字段 ---------order_detail表中添加小计
                $sqlt = "ALTER TABLE `mt_order_detail` ADD `count` INT (11) NOT NULL default '1'";
                $rest = Db::execute($sqlt);
            }

            //判断表中是否存在version字段
            $fiel = "SELECT * FROM information_schema.columns WHERE table_name='mt_store'  and column_name='version'";
            $field = Db::query($fiel);
           if($field == false){
                //插入表字段 ------store表中添加版本号
               $sqll = "ALTER TABLE `mt_store` ADD `version` VARCHAR (20) NOT NULL default '0'";
               $rest = Db::execute($sqll);
               if($rest > 0){//确定第一个版本号
                   $rst = Db::name('store')->where(["id"=>$uinfo['store_id']])->update(['version'=>'1.03']);
               }
           }else{
               $rst = Db::name('store')->where(["id"=>$uinfo['store_id']])->update(['version'=>'1.03']);
           }
            //获取上一次登录的时间
            $lasttime = $uinfo['last_login_time'];
            $time = strtotime(date("Y-m-d",time()));
            //获取该店铺是否存在今天已经登录
             $isFirst = Db::name("user")->where(["store_id"=>$uinfo['store_id']])->where("last_login_time",'>',$time)->count();
             if($isFirst < 1){
                 $this->success('账户同步，请等待...',url('api/Tongbu/firstLogin',array('username'=>$data['username'],'password'=>$data['password'])));
             }
//            $checkStore=Db::name("Store")->where("ownerid=".$uinfo['id'])->find();
            if($uinfo['store_id']){
                $userModel         = new UserModel();
                $user['user_pass'] = $data['password'];
                if (Validate::is($data['username'], 'email')) {
                    $user['user_email'] = $data['username'];
                    $log                = $userModel->doEmail($user);
                } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
                    $user['mobile'] = $data['username'];
                    $log            = $userModel->doMobile($user);
                } else {
                    $user['user_login'] = $data['username'];
                    $log                = $userModel->doName($user);
                }
                $redirect='/home/menu/menu';
                switch ($log) {
                    case 0:
                        cmf_user_action('login');
                        $this->redirect($redirect,lang('LOGIN_SUCCESS'));
                        break;
                    case 1:
                        $this->error(lang('PASSWORD_NOT_RIGHT'),0,0,0);
                        break;
                    case 2:
                        $this->error('账户不存在');
                        break;
                    case 3:
                        $this->error('账号被禁止访问系统');
                        break;
                    default :
                        $this->error('未受理的请求');
                }
            }else{
                $this->error('您没有权限登录店铺');
            }
        } else {
            $this->error("请求错误");
        }
    }

    /*
     *
     * 登录验证提交(用于同步)
     */
    public function doLogins()
    {
//        var_dump($this->request->param());exit();
        if ($this->request->param()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
                'password.max'     => '密码不能超过32个字符',
                'password.min'     => '密码不能小于6个字符',
            ]);

            $data = $this->request->param();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $passs = cmf_password($data['password']);
            $uinfo = Db::name("user")->where("mobile=".$data['username'])->find();
            if(empty($uinfo)){
                $this->error('账户不存在');exit;
            }
            //$checkStore=Db::name("Store")->where("ownerid=".$uinfo['id'])->find();
            if($uinfo['store_id']){
                $userModel         = new UserModel();
                $user['user_pass'] = $data['password'];
                if (Validate::is($data['username'], 'email')) {
                    $user['user_email'] = $data['username'];
                    $log                = $userModel->doEmail($user);
                } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
                    $user['mobile'] = $data['username'];
                    $log            = $userModel->doMobile($user);
                } else {
                    $user['user_login'] = $data['username'];
                    $log                = $userModel->doName($user);
                }
                $redirect='/home/menu/menu';
                switch ($log) {
                    case 0:
                        cmf_user_action('login');
                        $this->success(lang('LOGIN_SUCCESS'), $redirect);
                        break;
                    case 1:
                        $this->error(lang('PASSWORD_NOT_RIGHT'));
                        break;
                    case 2:
                        $this->error('账户不存在');
                        break;
                    case 3:
                        $this->error('账号被禁止访问系统');
                        break;
                    default :
                        $this->error('未受理的请求');
                }
            }else{
                $this->error('您没有权限登录店铺');
            }
        } else {
            $this->error("请求错误");
        }
    }


    /**
     * 找回密码
     */
    public function findPassword()
    {
        return $this->fetch('/find_password');
    }

    /**
     * 用户密码重置
     */
    public function passwordReset()
    {

        if ($this->request->isPost()) {
            $validate = new Validate([
                'captcha'           => 'require',
                'verification_code' => 'require',
                'password'          => 'require|min:6|max:32',
            ]);
            $validate->message([
                'verification_code.require' => '验证码不能为空',
                'password.require'          => '密码不能为空',
                'password.max'              => '密码不能超过32个字符',
                'password.min'              => '密码不能小于6个字符',
                'captcha.require'           => '验证码不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $captchaId = empty($data['_captcha_id']) ? '' : $data['_captcha_id'];
            if (!cmf_captcha_check($data['captcha'], $captchaId)) {
                $this->error('验证码错误');
            }

            $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }

            $userModel = new UserModel();
            if ($validate::is($data['username'], 'email')) {

                $log = $userModel->emailPasswordReset($data['username'], $data['password']);

            } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = $userModel->mobilePasswordReset($data['username'], $data['password']);
            } else {
                $log = 2;
            }
            switch ($log) {
                case 0:
                    $this->success('密码重置成功', $this->request->root());
                    break;
                case 1:
                    $this->error("您的账户尚未注册");
                    break;
                case 2:
                    $this->error("您输入的账号格式错误");
                    break;
                default :
                    $this->error('未受理的请求');
            }

        } else {
            $this->error("请求错误");
        }
    }

    public function logout(){
        session("user", null);//只有前台用户退出
        return redirect($this->request->root() . "/user/login/index");
    }
}